<template>
  <div>
    <el-upload
      action="#"
      list-type="picture-card"
      :on-remove="handleRemove"
      :file-list="fileList"
      :on-change="onChange"
      :http-request="onRequest"
      :on-preview="onPreview"
      :before-upload="beforeUpload"
      :limit="1"
      class="custom-upload"
      v-loading="loading"
      :class="fileList.length === 1 ? 'hideAdd' : ''"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="" />
    </el-dialog>
  </div>
</template>

<script>
import COS from "cos-js-sdk-v5";
const cos = new COS({
  SecretId: "AKIDoUDTjutiUIySkogJhsEQblyALTGyY0IM",
  SecretKey: "A6pKaH8mBLH1cz84oOm8JGzUtMvNckld",
});
export default {
  name: "UploadImg",
  data() {
    return {
      fileList: [],
      dialogVisible: false,
      dialogImageUrl: "",
      loading: false
    };
  },
  methods: {
    handleRemove(file, fileList) {
      this.fileList = fileList;
    },
    onChange(file, fileList) {
      this.fileList = fileList;
    },
    onRequest({ file }) {
      this.loading = true
      cos.putObject(
        {
          Bucket: "harry-1257539306" /* 填入您自己的存储桶，必须字段 */,
          Region: "ap-shanghai" /* 存储桶所在地域，例如ap-beijing，必须字段 */,
          Key: file.name /* 存储在桶里的对象键（例如1.jpg，a/b/test.txt），必须字段 */,
          StorageClass: "STANDARD",
          Body: file, // 上传文件对象
          onProgress: function (progressData) {
            console.log(JSON.stringify(progressData));
          },
        },
        (err, data) => {
          if (!err && data.statusCode === 200) {
            this.$emit('onSuccess', 'https://' + data.Location)
          }
          this.loading = false
        }
      );
    },
    onPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    beforeUpload(file) {
      // 检查文件类型
      const types = ["image/jpeg","image/png", "image/gif", "image/bmp"];
      if (!types.includes(file.type)) {
        this.$message.warning("上传的图片格式只能是JPG,GIF,BMP,PNG 格式!");
        return false;
      }
      // 检查大小
      const maxSize = 5 * 1024 * 1024;
      if (maxSize < file.size) {
        this.$message.warning("图片最大不能超过5M");
        return false;
      }
      return true;
    },
  },
};
</script>

<style lang="scss">
.hideAdd .el-upload--picture-card {
  display: none;
}
.custom-upload {
  width: 148px;
  height: 148px;
  overflow: hidden;
}
</style>